﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CSM.Controllers;
using CSM.Models;
using System.Text;

namespace CSM.Views.Kefu
{
    public partial class KefuMessage : CSMPageBase
    {
        CustomDataContext db = new CustomDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //查询当前操作员的店铺权限及客户回访等级权限。
                string MyUserId = HttpContext.Current.Session[SystemVars.sysSessionUserId].ToString();
                var RightList = from a in db.TCsm_JS_User
                                where a.UserID == MyUserId
                                select new
                                {
                                    a.ShopRightID

                                };
                if (RightList.Count() > 0)
                {

                    string MyShopRightIdList = RightList.Single().ShopRightID;
                    if (!string.IsNullOrEmpty(MyShopRightIdList))
                    {
                        var DropList_ShopRight = MyShopRightIdList.Split(',');
                        foreach (var MyItems in DropList_ShopRight)
                        {
                            var MyShopName = (from a in db.TCrm_JC_Parameter
                                              where a.ID == Convert.ToInt32(MyItems)
                                              select a).Single();
                            ListItem InsertItem = new ListItem(MyShopName.ShopName, MyShopName.ShopID);
                            //填充店铺列表
                            DropDownList_ShopId.Items.Add(InsertItem);

                        }

                    }
                }
            }
        }
        #region 绑定数据及翻页
        private void BindMyData(int PageIndex, string starts)
        {
            string ShopId = DropDownList_ShopId.SelectedValue;
            string picstring="<img alt=\"Pic\" src=\"pic.png\"/>";
            string txtstring = "<img alt=\"Txt\" src=\"txt.png\"/>";
            int skipAccount = PageIndex * 10;
            var MyQuery = (from a in db.VCrm_KF_Orders
                           where a.tid.StartsWith(starts) && a.seller_nick.Trim()==ShopId.Trim() orderby a.created descending
                           select new
                           {
                               Pic=(from c in db.TCrm_KF_CustomerSeviceInfo where c.OrderID==a.tid &&c.ImageUrl!=null select c).Count()==0?"":picstring,
                               Txt = (from c in db.TCrm_KF_CustomerSeviceInfo where c.OrderID == a.tid && c.Message != null select c).Count() == 0 ? "" :txtstring,
                               CustomerID=a.buyer_nick,
                               OrderID=a.tid,
                               OrderTime=a.created,
                               AliPayID=a.alipay_id,
                               Payment = string.Format("{0:N2}", a.payment),
                               PostPay = string.Format("{0:N2}", a.post_fee),
                               TotalPay = string.Format("{0:N2}", a.total_fee),
                               ReceiveAddress = (a.receiver_address.Length > 20 ? a.receiver_address.Substring(0, 20) + "..." : a.receiver_address),
                               MobleNum=a.receiver_mobile,
                               ReceiveName=a.receiver_name,
                               OrderStatus=a.status,
                           }  ).Skip(skipAccount).Take(10);
            GridView_Orders.DataSource = MyQuery;
            GridView_Orders.DataBind();
            if (MyQuery.Count() > 0)
            {
                Panel_Browse.Visible = true;
            }
            else
            {
                Panel_Browse.Visible = false;
                Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "message", " <script>alert('没有符合条件的记录'); </script>");
            }

        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount(string starts)
        {
            string ShopId = DropDownList_ShopId.SelectedValue;
            int MyQuery = 0;
            MyQuery = (from a in db.VCrm_KF_Orders
                           where a.tid.StartsWith(starts) &&a.seller_nick==ShopId select a).Count();
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void MyClick(object sender, EventArgs e)
        {


            int pageIndx = Convert.ToInt32(CurrentPage.Value);
            string starts = txtOrder.Text;
            int Totals = TotalPageAmount(starts);



            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            CurrentPage.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_CurrenPageAndTo.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";
            BindMyData(pageIndx, starts);

        }

        #endregion

        protected void Button_Save_Command(object sender, CommandEventArgs e)
        {
            TCrm_KF_CustomerSeviceInfo myrow = new TCrm_KF_CustomerSeviceInfo();
            string Creator=Session[SystemVars.sysSessionUserId].ToString();
            myrow.Message = TextBox_New.Text;
            myrow.CreateTime = DateTime.Now;
            myrow.OrderID = Label_ID.Text;
            myrow.UserID = Creator;
            db.TCrm_KF_CustomerSeviceInfo.InsertOnSubmit(myrow);
            db.SubmitChanges();
            string earlymessage = TextBox_Message.InnerHtml;
            string allstring="";
            allstring += Session[SystemVars.sysSessionUserId].ToString() + "" + DateTime.Now + "</br>";
            allstring +=TextBox_New.Text + "</br>";
            allstring = earlymessage + allstring;
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>Addhtml('"+allstring+"');</script>", false);
            //Response.AddHeader("Refresh", "0");
            
        }
        protected void Button_Cancel_Command(object sender, CommandEventArgs e)
        {
            Panel_Gridlist.Visible = true;
            Panel_Edit.Visible = false;
        }
        protected void Button_Message_Command(object sender, CommandEventArgs e)
        {
            string myOrderId = e.CommandArgument.ToString().Trim();
            Label_ID.Text = myOrderId;
            CustomId.Text = (from a in db.TCrm_KF_Orders where a.tid == myOrderId select a).First().buyer_nick;

            string UserId = Session[SystemVars.sysSessionUserId].ToString();
            string UserName = "?";
   
            var CurrentUserName = from a in db.TCsm_JS_User
                                  where a.UserID == UserId
                                  select a;
            if (CurrentUserName.Count() == 1)
            {
                UserName = CurrentUserName.Single().UserName;
            }



            Panel_Gridlist.Visible = false;
            var query = from a in db.TCrm_KF_CustomerSeviceInfo where a.OrderID == myOrderId orderby a.CreateTime descending select a;
            string allstring = "";
            //这个地方显示留言的时候，需要考虑格式。留言人，留言时间。
            foreach (var a in query)
            {
                allstring += UserName + "-(" + UserId + ")" + "  " + a.CreateTime + "</br>";
                if (a.Message != null)
                {
                    allstring += a.Message + "</br>";
                    allstring += "</br><hr class = \"hrcss_dashed\" />"; //增加一个分隔线，
                }
                else
                {
                }
                if (a.ImageUrl != null)
                {
                    string url = a.ImageUrl;
                    string temp = "<a href='" + url + "' id='thickbox'><img src='" + url + "' alt='Single Image'width='40px' height='60px'/></a>";
                    allstring += temp + "</br>";
                    allstring += "</br><hr class = \"hrcss_dashed\" />"; //增加一个分隔线，
                }
                else
                {
                }
            }
            TextBox_Message.InnerHtml = allstring;
            Panel_Edit.Visible = true;
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "订单明细信息", "<script>showfancy();</script>", false);
            ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "addtext", "<script>ShowThickBox_div('客服备注信息','Panel_Edit');</script>", false);
        }
       
        protected void Button_Browse_Click(object sender, EventArgs e)
        {
            string user = txtOrder.Text;
            BindMyData(0, user);
            int Totals = TotalPageAmount(user);
            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
            Label_Total.Text = "共" + pages.ToString();
            Label_CurrenPageAndTo.Text = "页，当前第1" + " 页，转到";
        }

        //显示当前订单的明细信息
        protected void Button_Detail_Command(object sender, CommandEventArgs e)
        {
            string myOrderId = e.CommandArgument.ToString().Trim();
            HiddenField_CurrentPage_OrderDetailId.Value = myOrderId;
            var MyQuery = (from a in db.TCrm_KF_Orders
                           where a.tid== myOrderId
                           select new
                           {
                               CustomerID=a.buyer_nick,
                               OrderID=a.oid,
                               OrderTime=a.created,
                               AliPayID=a.alipay_id,
                               Payment = string.Format("{0:N2}", a.payment),
                               PostPay = string.Format("{0:N2}", a.post_fee),
                               TotalPay = string.Format("{0:N2}", a.total_fee),
                               ReceiveAddress = (a.receiver_address.Length > 20 ? a.receiver_address.Substring(0, 20) + "..." : a.receiver_address),
                               MobleNum=a.receiver_mobile,
                               ReceiveName=a.receiver_name,
                               OrderStatus=a.status,
                               DeliveryStyle=a.shipping_type
                           });
            if (MyQuery.Count() != 0)
            {
                Panel_OrderDetail.Visible = true;

                var MyOrderRow  = MyQuery.First();
                TextBox_OrderId.Text = MyOrderRow.OrderID;
                TextBox_AliPay.Text = MyOrderRow.AliPayID;
                TextBox_CustomerId.Text = MyOrderRow.CustomerID;
                TextBox_DeliveryStyle.Text = MyOrderRow.DeliveryStyle;
                //TextBox_LogisticsCompany.Text = MyOrderRow.LogisticsCompany;
                //TextBox_LogisticsId.Text = MyOrderRow.LogisticsID;
                TextBox_MobleNum.Text = MyOrderRow.MobleNum;
                TextBox_OrderStatus.Text = MyOrderRow.OrderStatus;
                TextBox_Payment.Text = MyOrderRow.Payment;
                TextBox_ReceiveAddress.Text = MyOrderRow.ReceiveAddress;
                TextBox_ReceiveName.Text = MyOrderRow.ReceiveName;
                //TextBox_TotalPaid.Text = MyOrderRow.TotalPaid;
                TextBox_PostPay.Text = MyOrderRow.PostPay;
                TextBox_TotalPay.Text = MyOrderRow.TotalPay;
                BindMyData_OrderDetail(0, myOrderId);
                int Totals = TotalPageAmount_OrderDetail(myOrderId);
                int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);
                Label_OrderDetail_Total.Text = "共" + pages.ToString();
                Label_OrderDetail_ToPage.Text = "页，当前第1" + " 页，转到";


                ScriptManager.RegisterStartupScript((System.Web.UI.Page)HttpContext.Current.CurrentHandler, typeof(System.Web.UI.Page), "订单明细信息", "<script>ShowThickBox_div_OrderDetail('订单明细信息','Panel_OrderDetail');</script>", false);
            
            }
        

        }

        protected void Button_Detail_Cancel_Command(object sender, CommandEventArgs e)
        {
            Panel_OrderDetail.Visible = false;
        }
        #region 绑定当前订单的明细数据查询及翻页
        private void BindMyData_OrderDetail(int PageIndex, string OrderId)
        {
            int skipAccount = PageIndex * 10;
            var MyQuery = (from a in db.TCrm_KF_Orders
                           where a.tid == OrderId
                           select new
                           {
                               Number = string.Format("{0:N2}", a.num),
                               ProductID=a.outerid,
                               ProductName=a.item_title,
                               Price = string.Format("{0:N2}", a.payment),
                               SumMoney = Convert.ToDecimal(a.total_fee)
                           }).Skip(skipAccount).Take(10);
            GridView_OrderDetailList.DataSource = MyQuery;
            GridView_OrderDetailList.DataBind();

        }

        //查询出当前记录信息的总条数。
        private int TotalPageAmount_OrderDetail(string OrderId)
        {
            int MyQuery = 0;
            MyQuery = (from a in db.TCrm_KF_Orders
                       where a.tid == OrderId
                       select a).Count();
            return MyQuery;
        }


        //点击按钮，执行查询
        protected void OrderDetailClick(object sender, EventArgs e)
        {


            int pageIndx = Convert.ToInt32(HiddenField_CurrentPage_OrderDetail.Value);
            string MyOrderId = HiddenField_CurrentPage_OrderDetailId.Value.ToString();
            int Totals = TotalPageAmount_OrderDetail(MyOrderId);



            int pages = (Totals % 10) == 0 ? (Totals / 10) : (Totals / 10 + 1);

            Label_OrderDetail_Total.Text = "共" + pages.ToString();

            if (typeof(Button).IsInstanceOfType(sender))
            {
                string arg = ((Button)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "first":

                        pageIndx = 0;

                        break;
                    case "gotopage":
                        if (TextBox_PageIndex.Text == "")
                        { pageIndx = 0; }
                        else
                        {
                            int xx = Convert.ToInt32(TextBox_PageIndex.Text);
                            if (xx > pages)
                            { pageIndx = pages - 1; }

                            else
                            { pageIndx = xx - 1; }


                        }
                        break;
                }

            }
            else if (typeof(LinkButton).IsInstanceOfType(sender))
            {

                string arg = ((LinkButton)sender).CommandArgument.ToString().ToLower();

                switch (arg)
                {
                    case "prev":
                        if (pageIndx > 0)
                        {
                            pageIndx = pageIndx - 1;
                        }
                        break;
                    case "next":
                        if (pageIndx < pages - 1)
                        {
                            pageIndx = pageIndx + 1;
                        }
                        break;
                    case "last":
                        pageIndx = pages - 1;
                        break;
                    case "first":
                        pageIndx = 0;
                        break;
                }

            }

            HiddenField_CurrentPage_OrderDetail.Value = pageIndx.ToString();  //对保存页码状态信息的隐藏字段进行赋值。保存当前页码。
            Label_OrderDetail_ToPage.Text = "页，当前第" + (pageIndx + 1).ToString() + " 页，转到";

            BindMyData_OrderDetail(pageIndx, MyOrderId);

        }

        #endregion
    }
}
